//
//  RecordingViewController.m
//  sign Detector
//
//  Created by Oaf Tobark on 5/14/13.
//  Copyright (c) 2013 Thoi Thai. All rights reserved.
//

#import "RecordingViewController.h"
#import "SettingViewController.h"
#import "DataCenter.h"
#import "DetectorViewController.h"
#import "Recorder.h"
#import "LibraryViewController.h"
//#import <AVFoundation/AVFoundation.h>


#define COOKBOOK_PURPLE_COLOR [UIColor colorWithRed:0.000000 green:0.000000 blue:0.000000 alpha:0.1f]
#define BARBUTTON(TITLE, SELECTOR) [[UIBarButtonItem alloc] initWithTitle:TITLE style:UIBarButtonItemStylePlain target:self action:SELECTOR]
#define SYSBARBUTTON(ITEM, TARGET, SELECTOR) [[UIBarButtonItem alloc] initWithBarButtonSystemItem:ITEM target:TARGET action:SELECTOR]
#define IS_IPAD	(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

#define FILEPATH [DOCUMENTS_FOLDER stringByAppendingPathComponent:[self dateString]]


static RecordingViewController *_Share = nil;

@interface RecordingViewController (){
    IBOutlet UISwitch *_theSwitch;
    UIProgressView *power;
    UIButton *button;
    BOOL isRecording;
    Recorder *recorder;
    NSTimer *timer;
    IBOutlet UILabel *timeRecordLabel;
    IBOutlet UIButton *recordButton;
    IBOutlet UIButton *listButton;
    
}

- (IBAction)lockApp:(id)sender;

@end

@implementation RecordingViewController

+ (RecordingViewController*)shared{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!_Share) {
            _Share = [[RecordingViewController alloc] initWithNibName:@"RecordingViewController" bundle:[NSBundle mainBundle]];
        }
    });
    
    return _Share;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"Recorder...";
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStyleBordered target:self action:@selector(settings:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Records" style:UIBarButtonItemStyleBordered target:self action:@selector(records:)];
    if ([[DataCenter shared] appLock]) {
        _theSwitch.on = YES;
    }else{
        _theSwitch.on = NO;
    }
    self.navigationItem.titleView = _theSwitch;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSString *) dateString
{
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	formatter.dateFormat = @"ddMMYY_hhmmssa";
	return [[formatter stringFromDate:[NSDate date]] stringByAppendingString:@".aif"];
}

- (NSString *) formatTime: (int) num
{
	int secs = num % 60;
	int min = num / 60;
	
	if (num < 60) return [NSString stringWithFormat:@"0:%02d", num];
	
	return	[NSString stringWithFormat:@"%d:%02d", min, secs];
}


- (void) updateStatus
{
	power.progress = recorder.averagePower;
	timeRecordLabel.text = [self formatTime:recorder.currentTime];
}


- (void) pauseRecording
{
	if (recorder && recorder.isRecording)
	{
		[recorder pause];
		recordButton.selected = YES;
        listButton.selected = YES;
	}
}

- (void) resumeRecording
{
	if (recorder && recorder.isRecording)
	{
        recordButton.selected = YES;
        listButton.selected = YES;
		[recorder resume];
	}
}


#pragma mark - Private Methods

- (void)settings:(id)sender{
    NSLog(@"Push to settings");
    if ([self.navigationController.viewControllers containsObject:[SettingViewController shared]]) {
        [self.navigationController popToViewController:[SettingViewController shared] animated:YES];
    }else{
        [self.navigationController pushViewController:[SettingViewController shared] animated:YES];
    }
}

- (IBAction)records:(id)sender {
    // Establish recorder
	if (!recorder)
        recorder = [[Recorder alloc] init];
    
	if (!recorder)
	{
		NSLog(@"Error: Could not create recorder");
		return;
	}
	
	if (!isRecording)
	{
		BOOL success = [recorder startRecording:FILEPATH];
		if (!success)
		{
			printf("Error starting recording\n");
			[recorder stopRecording];
			recorder = nil;
			isRecording = NO;
			return;
		}
	}
	else
	{
		[recorder stopRecording];
		recorder = nil;
		self.title = nil;
	}
	
	isRecording = !isRecording;
    
	// Handle the GUI updates
	if (isRecording)
	{
		// start monitoring the power level
		timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(updateStatus) userInfo:nil repeats:YES];
        recordButton.selected = YES;
        listButton.selected = YES;
		self.navigationItem.leftBarButtonItem = SYSBARBUTTON(UIBarButtonSystemItemPause, self, @selector(pauseRecording));
	}
	else
	{
		// Stop monitoring the power level
		power.progress = 0.0f;
		[timer invalidate];
		timer = nil;
        recordButton.selected = NO;
        listButton.selected = NO;
	}
    
}

- (IBAction)lockApp:(id)sender{
    if (_theSwitch.on == NO) {
        [[DataCenter shared] lock:^{
            if ([self.navigationController.viewControllers containsObject:[DetectorViewController shared]]) {
                [self.navigationController popToViewController:[DetectorViewController shared] animated:YES];
            }else{
                [self.navigationController pushViewController:[DetectorViewController shared] animated:YES];
            }
        }];
    }    
}

- (IBAction)library:(id)sender {
    // stop any current recording
	if (isRecording)
	{
        recordButton.selected = NO;
        listButton.selected = NO;
		self.navigationItem.leftBarButtonItem = nil;
		[recorder stopRecording];
		recorder = nil;
		self.title = nil;
		isRecording = NO;
	}
	
	// stop power monitoring
	[timer invalidate];
	timer = nil;
	
	// push the library controller
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed" message:@"Library crash... comming soon ^^" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    
//    [alert show];
    LibraryViewController *controller = [[LibraryViewController alloc] initWithNibName:@"LibraryViewController" bundle:nil];
	[self.navigationController pushViewController:controller animated:YES];
}



- (void)viewDidUnload {
    timeRecordLabel = nil;
    recordButton = nil;
    listButton = nil;
}
@end
